﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AE.Net.Mail;
using System.IO;
using AXSMSCFGLib;

namespace GetMessagesFromGmail
{
    class Program
    {
        static void Main(string[] args)
        {
            IXMessageDB objMessageDB;
            IXConstants objConstants;

            objMessageDB = new XMessageDB();
            objConstants = new XConstants();

            String user_name = System.Configuration.ConfigurationSettings.AppSettings["user_name"];
            String password = System.Configuration.ConfigurationSettings.AppSettings["password"];
            String read_label = System.Configuration.ConfigurationSettings.AppSettings["read_label"];
            String failure_label = System.Configuration.ConfigurationSettings.AppSettings["fail_label"];

            Console.WriteLine("Fetching emails from Gamil Inbox...");
            ImapClient imap = new ImapClient("imap.gmail.com", user_name, password, ImapClient.AuthMethods.Login, 993, true);
            Console.WriteLine("Emails has been successfully fetched.");

            String response = String.Empty;

            try
            {
                imap.SelectMailbox("INBOX");
                int count = imap.GetMessageCount();
                
                String subject = String.Empty;
                String body = String.Empty;

                if (count > 0)
                {
                    MailMessage[] messages = imap.GetMessages(0, count - 1, false, false);

                    foreach (MailMessage message in messages)
                    {
                        subject = message.Subject;
                        body = GetBody(message.BodyHtml);
                        
                        String[] contacts = subject.Split(',');
                        try
                        {
                            for (int i = 0; i < contacts.Length; i++)
                            {
                                String contact = contacts[i];

                                if (contact.StartsWith("0"))
                                    contact = "+92" + contact.Substring(1, contact.Length - 1);

                                Console.WriteLine(String.Format("{0}  {1} Sending Message {2}", (i + 1).ToString(), contact, body));

                                objMessageDB.Open();

                                if (objMessageDB.LastError > 0)
                                {
                                    Console.WriteLine("Failed to open message database, error: {0}", objMessageDB.LastError);
                                    imap.MoveMessage(message.Uid, failure_label);
                                    return;
                                }

                                object ob = (object)objMessageDB.Create();
                                IXMessage objMessage = (IXMessage)ob;

                                if (objMessageDB.LastError > 0)
                                {
                                    Console.WriteLine("Create Failed, error: {0}", objMessageDB.LastError);
                                    imap.MoveMessage(message.Uid, failure_label);
                                    return;
                                }

                                Console.WriteLine("Message successfully created, recordID: {0}", objMessage.ID);

                                objMessage.Direction = objConstants.MESSAGEDIRECTION_OUT;
                                objMessage.Type = objConstants.MESSAGETYPE_SMS;
                                objMessage.Status = objConstants.MESSAGESTATUS_PENDING;
                                objMessage.ChannelID = 0;
                                objMessage.ScheduledTime = "";
                                objMessage.Recipient = contact;
                                objMessage.Body = body;

                                objMessageDB.Save(ref ob);

                                if (objMessageDB.LastError > 0)
                                {
                                    Console.WriteLine("Update message failed, error: {0}", objMessageDB.LastError);
                                    imap.MoveMessage(message.Uid, failure_label);
                                    return;
                                }

                                objMessageDB.Close();
                            }
                        }
                        catch (Exception exc)
                        {
                            imap.MoveMessage(message.Uid, failure_label);
                        }

                        imap.MoveMessage(message.Uid, read_label);
                    }
                }

                imap.Disconnect();
            }
            catch (Exception ex)
            {
                Console.WriteLine(String.Format("Exception: \n{0}\n{1}", ex.Message, ex.StackTrace));   
            }

        }

        private static String GetBody(String body)
        {
            while (body.Contains(">") || body.Contains("<"))
            {
                int index1 = body.IndexOf("<");
                int index2 = body.IndexOf(">");

                body = body.Substring(0, index1) + body.Substring(index2 + 1, body.Length - index2 - 1);
            }

            body = body.Replace("\r\n", "").Replace("  ", " ");

            return body;
        }
    }
}
